<?php
/**
 * kol红人产品
 * User: bgl
 * Date: 2023/3/13
 * Time: 10:06
 */

namespace App\Admin\Controllers\KolManage;

use App\Admin\Ajax\KolManage\KolSkuAjax;
use App\Admin\Controllers\ErpController;
use App\Models\KolManage\Kol;
use App\Models\KolManage\KolSku;
use App\Models\Product\ProductClassify;
use App\Models\Product\ProductSku;
use App\Util\RExcel;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;

class KolSkuController extends ErpController{

    protected $title = 'Kol红人产品列表（sku）';

    protected $filters = [
        'sku' => null,
        'kol_id' => null,
        'classify_id' => null,
        'season' => null,
        'status' => null,
    ];

    protected function grid(){

        $filters = $this->getFilters();
        $this->initFilters($filters);
        $query = $this->_initQuery($filters);
        $paginator = $this->paginator($query);
        $action = $this->getAction();
        $filtersBlade = [];
        $filtersBlade['sku'] = $this->filters['sku'];
        $filtersBlade['kol_id'] = getOptions(Kol::options(),$this->filters['kol_id']);
        $filtersBlade['classify_id'] = getOptions(ProductClassify::options(),$this->filters['classify_id']);
        $filtersBlade['season'] = getOptions(ProductClassify::$_season,$this->filters['season']);
        $filtersBlade['status'] = getOptions(KolSku::$_status,$this->filters['status']);

        $downloadUrl = $this->getDownloadUrl('/xqc/kol-manage/kol-sku-download');

        return view('kol-manage.kol-sku.list.index', compact('paginator','action','filtersBlade','downloadUrl'));
    }

    private function _initQuery($filters){

        $query = KolSku::query()->orderBy('id', 'DESC');
        foreach ($filters as $field => $filter){
            if(!$filter)continue;

            if($field == 'sku'){
                $query->whereHas('sku', function ($query) use($filter){
                    $query->where('psku_code', 'like', "%{$filter}%")
                        ->orWhere('psku_cn', 'like', "%{$filter}%");
                });
            }
            if($field == 'classify_id'){
                $query->whereHas('sku', function ($query) use($filter){
                    $query->where('classify_id', $filter);
                });
            }

            if(in_array($field,['kol_id','name','status'])){
                $query->where($field,$filter);
            }
        }
        return $query;
    }

    public function ajax(){
        $ajax = new KolSkuAjax();
        return $this->callAjax($ajax);
    }

    public function download(){
        $filters = $this->getFilters();
        $query = $this->_initQuery($filters);
        $this->_exeDownload($query);
    }

    private function _exeDownload($query){
        $head = ['kol账号','sku','sku名称','品类名称','季节性','备注','状态'];
        RExcel::exportCsv('红人产品信息', function () use ($head, $query) {
            $fp = fopen('php://output', 'w');
            fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
            fputcsv($fp, $head);
            $query->chunk(1000, function ($re) use ($fp){
                $data = KolSku::getDownloadData($re);
                foreach ($data as $item) {
                    fputcsv($fp, $item);
                }
            });
        });
    }

    protected function form(){

        $form = new Form(new KolSku());

        $form->tools(function (Form\Tools $tools){
            $tools->disableView();
        });

        $form->hidden('id');

        $form->select('kol_code', 'kol账号')
            ->options(Kol::options())
            ->required()->rules("required")->setWidth(5);

        //------select联动-------
        $form->select('classify_id', '产品品类')
            ->options(ProductClassify::options(['status', ProductClassify::SYNC_YES]))
            ->load('psku_id','/xqc/api-sys/sku-list')
            ->required()->setWidth(5);

        $form->select('psku_id','产品名称')->options(function ($id) {
            return ProductSku::query()->where('id',$id)->pluck('psku_cn', 'id');
        })->required()->setWidth(5);
        //-----------------------

        $form->textarea('remark', '备注')->setWidth(5);
        $form->radio('status', '状态')->options(KolSku::$_status)->default(1)->setWidth(5);
        $form->hidden('admin_id')->value(Admin::user()->id);


        if($form->isCreating()){
            $form->disableCreatingCheck(false);
        }
        $form->saving(function (Form $form) {
            $count = KolSku::query()
                ->where('id', '<>', $form->model()->id)
                ->where('kol_code', $form->kol_code)
                ->where('psku_id', $form->psku_id)
                ->count();
            if($count > 0){
                admin_error('重复添加', '该产品已存在');
                return back()->withInput();
            }
        });

        $form->tools(function (Form\Tools $tools) {
            $tools->disableDelete();
        });
        return $form;
    }

}
